<template>
    <el-dialog v-model="dialogVisible" title="分配权限" width="50%" :before-close="handleClose">
        <div>
            <el-tree :data="data" show-checkbox node-key="id" :default-expanded-keys="defaultExpandedKeys"
                :default-checked-keys="defaultCheckedKeys" :props="defaultProps"  ref="treeRef"/>
        </div>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="handleClose">取消</el-button>
                <el-button type="primary" @click="comfire">确定</el-button>
            </span>
        </template>
    </el-dialog>
</template>
<script setup>
import {getRightsList,setRights} from '../../../api/role.js'
import { ref } from 'vue';
import children from '../../../router/children.js';
import showElemessage from '../../../tools/showElemessage.js';
let dialogVisible = ref(false);
let handleClose = () => {
    dialogVisible.value = false;
}
const defaultProps = {
  children: 'children',
  label: 'authName',
}
// 角色id
let role_Id = ref(null)
const data =ref([])
// 存放要展开的权限id (一级 二级权限id)
let defaultExpandedKeys = ref([]);
// 存放默认选中的id
let defaultCheckedKeys = ref([]);
// 定义组件初始化方法
let init = async (children,id)=>{
    role_Id.value = id;
    defaultExpandedKeys.value = [];
    defaultCheckedKeys.value=[]
    console.log(children)
    dialogVisible.value= true;
    let res = await getRightsList('tree');
    console.log(res)
    data.value = res.data.data;

      // 处理权限数据将要展开的权限和选中的权限过滤
    children.forEach(item=>{
        defaultExpandedKeys.value.push(item.id);
        item.children.forEach(item1=>{
                 defaultExpandedKeys.value.push(item1.id);
                 item1.children.forEach(item2=>{
                    defaultCheckedKeys.value.push(item2.id)
                 })
        })
    })
    console.log(defaultExpandedKeys)
    console.log(defaultCheckedKeys)
    }
defineExpose({
    init
})
let treeRef = ref(null)
let emit = defineEmits(['over'])
// 分配权限
let comfire = async ()=>{
    // console.log(treeRef.value)
    // 获取全选项
    let allKeys = treeRef.value.getCheckedKeys();
    // console.log(allKeys)
    // 获取半选中key 
    let halfKeys=treeRef.value.getHalfCheckedKeys();
    // console.log(halfKeys)
    let keys  = [...allKeys,...halfKeys];
    let rids = keys.join(',')
    console.log(rids)
    let res = await setRights(role_Id.value,{rids:rids});
    console.log(res)
    handleClose();
    showElemessage("分配成功",'success',2000)
    emit('over')
}
</script>